package com.westos.echufang.controller;

import com.westos.echufang.constants.RegistConstants;
import com.westos.echufang.pojo.vo.Regist;
import com.westos.echufang.service.regist.RegistServiceImpl;
import com.westos.echufang.utils.CookieUtil;
import com.westos.echufang.utils.EmailUtil;
import com.westos.echufang.utils.MultipartFileUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Objects;

@Controller

public class RegistController {

    @Value("${imagePath}")
    private String imagePath;

    private final
    RegistServiceImpl registService;

    private final EmailUtil emailUtil;

    private final MultipartFileUtil multipartFileUtil;
    private final CookieUtil cookieUtil;

    @Autowired
    public RegistController(RegistServiceImpl registService, EmailUtil emailUtil, MultipartFileUtil multipartFileUtil, CookieUtil cookieUtil) {
        this.registService = registService;
        this.emailUtil = emailUtil;
        this.multipartFileUtil = multipartFileUtil;
        this.cookieUtil = cookieUtil;
    }


    @RequestMapping(value = "/canRegist", method = RequestMethod.POST)
    public String canRegist(Regist regist, @RequestParam("certificate") MultipartFile certificate, Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        File staticFile = new File(ResourceUtils.getURL("classpath:").getPath() + imagePath);
        if (!staticFile.exists())
            staticFile.mkdirs();
        if (regist != null) {
            if (!regist.getJob().equals("admin")) {
                if (!certificate.isEmpty()) {
                    File file = new File(ResourceUtils.getURL("classpath:").getPath() + imagePath, (regist.getPhone().concat(Objects.requireNonNull(certificate.getOriginalFilename()))));
                    if (!file.exists()) {
                        session.setAttribute("file", file);
                        session.setAttribute("certificate", certificate.getBytes());
                    } else {
                        model.addAttribute("registError", "用户已存在，请登录或重新注册");
                        return "regist/regist";
                    }

                } else {
                    model.addAttribute("registError", "注册失败，请重新注册");
                    return "regist/regist";
                }

            }


            Integer canRegist = registService.canRegist(regist);
            String email = regist.getEmail().trim();
            String phone = regist.getPhone().trim();
            if (canRegist.equals(RegistConstants.CAN_REGIST)) {
                Cookie regEmail = null;
                Cookie regCode = null;
                Cookie regPhone = null;
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    switch (cookie.getName()) {
                        case "regEmail":
                            regEmail = cookie;
                            break;
                        case "regCode":
                            regCode = cookie;
                            break;
                        case "regPhone":
                            regPhone = cookie;
                            break;
                    }
                }
                session.setAttribute("regist", regist);


                if (regEmail == null || regCode == null || regPhone == null || !regPhone.getValue().equals(phone)) {
                    String code = RandomStringUtils.random(8, false, true);
                    emailUtil.send1(email, code);
                    regEmail = new Cookie("regEmail", email);
                    regCode = new Cookie("regCode", code);
                    regPhone = new Cookie("regPhone", phone);
                    regEmail.setMaxAge(60 * 30);
                    regCode.setMaxAge(60 * 30);
                    regPhone.setMaxAge(60 * 30);
                    regEmail.setHttpOnly(true);
                    regCode.setHttpOnly(true);
                    regPhone.setHttpOnly(true);
                    response.addCookie(regEmail);
                    response.addCookie(regCode);
                    response.addCookie(regPhone);
                    session.setAttribute("regEmailAdress", "验证码已发送至" + new StringBuilder(email).replace(4, email.indexOf("@"), "******"));
                    return "regist/mailCheck";
                } else {
                    session.setAttribute("regEmailAdress", "验证码已发送至" + new StringBuilder(email).replace(4, regEmail.getValue().indexOf("@"), "******"));
                    return "regist/mailCheck";
                }
            } else {
                model.addAttribute("registError", "用户已存在，请登录或重新注册");
                return "regist/regist";
            }
        } else {
            model.addAttribute("registError", "注册失败，请重新注册");
            return "regist/regist";
        }
    }


    // TODO: 添加注册后邮箱验证
    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    public String regist(@RequestParam("code") String code, HttpSession session, Model model, @CookieValue("regEmail") Cookie regEmail, @CookieValue("regCode") Cookie regCode, @CookieValue("regPhone") Cookie regPhone, HttpServletResponse response) throws IOException {
        Regist regist = (Regist) session.getAttribute("regist");
        File file = (File) session.getAttribute("file");
        byte[] certificate = (byte[]) session.getAttribute("certificate");
        String job = regist.getJob();


        if (code.equals(regCode.getValue())) {
            Integer registMsg;
            switch (job) {
                case "admin":
                    registMsg = registService.registEmp(regist, "");
                    break;
                case "doctor":
                case "pharmacist":
                    registMsg = registService.registEmp(regist, file.getName());
                    break;
                default:
                    model.addAttribute("registError", "注册失败，请重新注册");
                    return "regist/regist";
            }
            if (registMsg.equals(RegistConstants.REGIST_SUCCESS_EMPLOYEE)) {
                if (multipartFileUtil.toFile(file, certificate)) {
                    cookieUtil.removesCookies(response, regEmail, regCode, regPhone);
                    session.removeAttribute("regist");
                    return "redirect:/registSuccess";
                } else {
                    model.addAttribute("registError", "注册失败，请重新注册");
                    return "regist/regist";
                }

            } else if (registMsg.equals(RegistConstants.REGIST_SUCCESS_ADMIN)) {
                cookieUtil.removesCookies(response, regEmail, regCode, regPhone);
                session.removeAttribute("regist");
                return "redirect:/registSuccess";
            } else {
                model.addAttribute("registError", "照片上传失败，请重新注册");
                return "regist/regist";
            }
        } else {
            model.addAttribute("mailCheck", "验证码错误");
            return "regist/mailCheck";
        }
    }
}








